<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var kWeakestRows = function (mat, k) {
      const array = []
      //先遍历矩阵，把每一行士兵数整理出来
      for (let i = 0; i < mat.length; i++) {
        let army = 0
        for (let j = 0; j < mat[i].length; j++) {
          if (mat[i][j]) {
            army++
          }
        }
        //array数组也是个二维数组，每一行都是表示mat矩阵的行与该行士兵数
        //这里用二维数组主要是为了记录行号与行号所包含的士兵数，用一维数组会丢失行号
        array.push([i, army])
      }
      //按照士兵数排正序
      array.sort((a, b) => a[1] - b[1])
      const res = []
      //读取前K行的行号作为返回值
      for (let i = 0; i < k; i++) {
        res.push(array[i][0])
      }
      return res
    };
    console.log(kWeakestRows(mat =
      [[1, 0, 0, 0],
      [1, 1, 1, 1],
      [1, 0, 0, 0],
      [1, 0, 0, 0]],
      k = 2))
  </script>
</body>

</html>